<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Model\Message;
use App\Model\PushMessage;
use App\Model\User;
use App\Model\UserProfile;
use App\Util\ImUtil;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Log;

class PushMessageController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('Push消息推送');
            $content->description('');
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('Push消息推送');
            $content->description('');
            $content->body($this->form('edit', $id)->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('Push消息推送');
            $content->description('');
            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(PushMessage::class, function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $grid->id('推送消息ID');
            $grid->push_user_ids('用户ID');
            $grid->push_title('推送标题');
            $grid->push_content('推送内容');
            $grid->push_gender('发送性别')->display(function ($gender) {
                return $gender == 1 ? '男' : ($gender == 0 ? '女' : '-');
            });
            // $grid->push_recharge('发送用户是否充值')->display(function ($data) {
            //     return $data == 1 ? '充值用户' : ($data == 0 ? '非充值用户' : '全部');
            // });
            $grid->push_role('发送用户角色')->display(function ($data) {
                return $data == UserProfile::ROLE_HOST ? '认证女用户' : ($data == UserProfile::ROLE_USER ? '普通用户' : '不限');
            });
            $grid->push_type('发送内容类型')->display(function ($data) {
                return PushMessage::TYPE[$data];
            });
            $grid->jump_type('配置跳转类型')->display(function ($data) {
                return PushMessage::JUMP_TYPE[$data];
            });
            $grid->jump_link('跳转链接');
            $grid->flag('消息状态')->display(function ($data) {
                return $data == 1 ? '有效' : '无效';
            });
            $grid->created_at('创建时间')->display(function ($time) {
                return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
            });
            //禁用导出
            $grid->disableExport();
            $grid->disableActions();
            //禁用行选择
            $grid->disableRowSelector();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();
            });

            $grid->filter(function ($filter) {
                $filter->expand();
                $filter->disableIdFilter();
                $filter->column(1 / 3, function ($filter) {
                    $filter->contains('push_user_ids', '用户ID');
                });
            });
        });
    }

    /**
     * bi
     * @return Form
     */
    protected function form()
    {
        return Admin::form(PushMessage::class, function (Form $form) {
            $form->textarea('push_user_ids', '发送用户ID')->rows(10)->default(0);
            $form->select('push_gender', '发送性别')->default(-1)->options([0 => '女', 1 => '男', -1 => '不限']);
            // $form->select('push_recharge', '发送用户是否充值')->default(-1)->options([-1 => '全部', 1 => '充值用户', 0 => '非充值用户']);
            $form->select('push_role', '发送用户角色')->default(-1)->options([-1 => '不限', UserProfile::ROLE_HOST => '认证女用户', UserProfile::ROLE_USER => '普通用户']);
            $form->select('push_type', '发送内容类型')->default(1)->options(PushMessage::TYPE)->required();
            $form->text('push_title', '推送标题')->placeholder('最多可输入20个字符')->default('官方通知')->required();
            $form->textarea('push_content', '推送内容')->placeholder('最多可输入500个字符')->default('恭喜你成功注册软件，希望你在这好好享受交友的魅力~')->required();
            $validJumpTypes = PushMessage::JUMP_TYPE;
            $form->select('jump_type', '配置跳转类型')->default('h5')->options($validJumpTypes)->required();
            // $form->text('jump_link', '跳转链接')->placeholder('用户主页和动态则分别输入：用户ID和动态ID')->default('');
            $form->tools(function (Form\Tools $tools) {
                $tools->disableDelete();
                $tools->disableView();
                $tools->disableList();
            });
            $form->saving(function (Form $form) {
                switch ($form->jump_type) {
                    case PushMessage::JUMP_TYPE_SOCIAL_PROFILE:
                        $form->jump_link = '';
                        break;
                    default:
                        $form->jump_link = '';
                }
            });

            $form->saved(function (Form $form) {
                $model = $form->model();
                $profileUserIds = $model->push_user_ids == 0 ? [] : explode("\r\n", $form->push_user_ids);
                $gender = $model->push_gender;
                $role = $model->push_role;
                $pushType = $model->push_type;
                //获取相应的用户
                $userIds = PushMessage::selectUserIds($gender, $role, 0, $profileUserIds);
                //根据资料ID获取用户ID
                // $userIds = UserProfile::getUidByProfileId($profileUserIds);
                Log::info(__CLASS__ . "==PushType:{$pushType}==UserIds:" . count($userIds));

                if (!$userIds) $this->error('推送用户不存在！');
                // return false;

                //消息格式
                $msgContent = PushMessage::buildMsgContent($model);
                //推送消息
                switch ($pushType) {
                        //官方推送
                    case PushMessage::TYPE_APP:
                        $msgType = $model->jump_type == PushMessage::JUMP_TYPE_SOCIAL_PROFILE ? PushMessage::MSG_TYPE_TEXT_LINK : PushMessage::MSG_TYPE_TEXT;
                        Message::pushOfficial($userIds, $msgContent, $msgType);
                        break;
                        //纯push
                    case PushMessage::TYPE_PUSH:
                        Message::sendPush($userIds, $model->push_title, $msgContent);
                        break;
                        //系统通知
                    case PushMessage::TYPE_SYS:
                        Message::pushSystem($userIds, $msgContent['text'], $model->push_title);
                        break;
                }
                // \Log::info(__CLASS__ . "==PushType:{$pushType}==UserIds:" . json_encode($userIds) . "==MsgContent:" . json_encode($msgContent));
            });
        });
    }
}
